package util

import (
	"errors"
	"github.com/shopspring/decimal"
)

func CopyMap(source map[string]interface{}) map[string]interface{} {
	if source == nil {
		return nil
	}
	var dest = map[string]interface{}{}
	for k, v := range source {
		dest[k] = copyItem(v)
	}
	return dest
}

func CopyArray(source []interface{}) []interface{} {
	if source == nil {
		return nil
	}
	var dest = make([]interface{}, len(source))
	for i, v := range source {
		dest[i] = copyItem(v)
	}
	return dest
}

func copyItem(v interface{}) interface{} {
	switch v.(type) {
	case map[string]interface{}:
		return CopyMap(v.(map[string]interface{}))
	case []interface{}:
		return CopyArray(v.([]interface{}))
	default:
		return v
	}
}

func Compare(_a, _b interface{}) (int, error) {
	var a, ok0 = _a.(decimal.Decimal)
	var b, ok1 = _b.(decimal.Decimal)
	if ok0 && ok1 {
		return a.Cmp(b), nil
	}
	return -100, errors.New("错误的对比")
}

func Equal(_a, _b interface{}) bool {
	if _a == nil && _b == nil {
		return true
	}
	switch _a.(type) {
	case string:
		switch _b.(type) {
		case string:
			return _a.(string) == _b.(string)
		}
	case decimal.Decimal:
		switch _b.(type) {
		case decimal.Decimal:
			return _a.(decimal.Decimal).Equals(_b.(decimal.Decimal))
		//针对_id的特殊处理
		case string:
			var db, err = decimal.NewFromString(_b.(string))
			if err != nil {
				return false
			}
			return _a.(decimal.Decimal).Equals(db)
		}
	}
	return false
}
